<?php
class Mysql
{
	public $link; // MySQL连接标识 
	public $dbPrefix;  //表前缀

	public function __construct($config)
	{
		$this->link = @mysql_connect ($config['hostname'],$config['username'], $config['password'], true);
		$this->dbPrefix = $config['tablepre'];
		if ($this->link) {
			mysql_select_db ($config['database'], $this->link );
			$charset = str_replace ( '_', '', $config['charset']);
			mysql_query ( "SET NAMES '$charset'", $this->link );
		} else {
			$this->throwException ( 'MySQL server error report!' );
		}
	}
   
	/**
	 * @todo 执行SQL语句
	 * @param string $sql
	 * @param array $args
	 */
	public function query($sql)
    {
//		echo $sql;
//		echo "<hr>";
    	$rs = mysql_query($sql, $this->link);
        return $rs;
    }
	
	/**
	 * 返回结果集的数组形式
	 * @return array
	 */
	function fetch_array($rs, $result_type = MYSQL_ASSOC)
	{
		return mysql_fetch_array ( $rs, $result_type );
	}
	
	//	 * 返回结果集的数组形式row
	public function fetch_row($rs)
	{
		return mysql_fetch_row ($rs);
	}
	
	/**
	 * 执行一条SQL语句返回是否成功
	 * @param string $sql  SQL语句
	 * @return boolean
	 */
	public function execute($sql)
    {
        if ($this->query($sql)) {
            return true;
        } else {
            return false;
        }
    }
	
	/**
	 * 得到结果集的第一个数据
	 * @param string $sql   SQL语句
	 * @return mixed
	 */
	public function getOne($sql)
    {
        if (!$rs = $this->query($sql)) {
            return false;
        }
        $row = $this->fetch($rs);
        $this->free($rs);
        return is_array($row) ? array_shift($row) : $row;
    }
	
	/**
	 * 返回结果集的一行
	 * @param string $sql  SQL语句
	 * @return mixed
	 */
	public function getRow($sql)
    {
        if (!$rs = $this->query($sql)) {
            return false;
        }
        $row = $this->fetch($rs);
        $this->free($rs);
        return $row;
    }
	
	/**
	 * 返回所有结果集
	 * @param string $sql   SQL语句
	 * @param string $limit SQL语句的LIMIT限制
	 * @return mixed
	 */
	public function getAll($sql)
    {
        if (!$rs = $this->query($sql)) {
            return false;
        }
        $all_rows = array();
        while ($rows = $this->fetch($rs)) {
            $all_rows[] = $rows;
        }
        $this->free($rs);
        return $all_rows;
    }
    /**
	 * 取所有行的第一个字段信息
	 * @param string $sql   SQL语句
	 * @return array
	 * @access public
	 */
    public function getCol($sql)
    {
        $res = $this->query($sql);
        if ($res !== false) {
            $arr = array();
            while ($row = mysql_fetch_row($res)) {
                $arr[] = $row[0];
            }
            return $arr;
        } else {
            return false;
        }
    }
	/**
	 * 执行INSERT命令.返回AUTO_INCREMENT
	 * @param string $table  表名称
	 * @param string $dataArray  数据
	 * @return boolean
	 */
    public function insert($table,$dataArray)
    {
        $field = "";
		$value = "";
		if( !is_array($dataArray) || count($dataArray)<=0) {
			return false;
		}
		while(list($key,$val)=each($dataArray)) {
			$field .="$key,";
			$value .="'$val',";
		}
		$field = substr( $field,0,-1);
		$value = substr( $value,0,-1);
		$sql = "insert into $table($field) values($value)";
//		echo $sql;
		if(!$this->query($sql)) return false;
		return $this->insert_id();
    }
	 
	public function insert_id()
	{
		return mysql_insert_id ( $this->link );
	}
	
	//更新
	public function update($table,$dataArray,$condition="") 
	{
		if( !is_array($dataArray) || count($dataArray)<=0) return false;
	
		$value = "";
		while( list($key,$val) = each($dataArray))
		$value .= "$key = '$val',";
		$value = substr( $value,0,-1);
		$sql = "update $table set $value where 1=1 and $condition";
		//echo $sql;
		if(!$this->query($sql)) return false;
		return $this->affected_rows();
	}
	
	public function affected_rows(){
	    return mysql_affected_rows($this->link);
	}

	//删除
	public function delete($table,$condition="") 
	{
		if( empty($condition) ) return false; 
		$sql = "delete from $table where 1=1 and $condition";
		if(!$this->query($sql)) return false;
		return $this->affected_rows();
	}
	public function num_rows($results) {
		if(!is_bool($results)) {
			$num = mysql_num_rows($results); 
			return $num;
		} else {
			return 0;
		}
	}
	/**
	 * 执行INSERT命令.返回AUTO_INCREMENT
	 * 返回0为没有插入成功
	 *
	 * @param string $sql  SQL语句
	 * @access public
	 * @return integer
	 */
	public function autoInsert($sql)
	{
		if($this->execute($sql)){
			return mysql_insert_id($this->link);
		}else{
		    return false;
		}
	}
	/**
     * insert For Mysql return 有返回值 返回mysql_insert_id
     * @param <type> $table
     * @param <type> $field_values
     * @param <type> $mode
     * @param <type> $where
     * @return <type>
     */
	public function autoInsertReturn($table, $field_values)
	{
		$field_names = $this->getCol('DESC ' . $table);
	
		$sql = '';
		$fields = $values = array();
		foreach ($field_names AS $value) {
			if (array_key_exists($value, $field_values) == true) {
				$fields[] = '`' . $value . '`';
				$values[] = "'" . $field_values[$value] . "'";
			}
		}
	
		if (!empty($fields)) {
			$sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
		}
	
		if ($sql) {
			return $this->autoInsert($sql);
		} else {
			return false;
		}
	}
	/**
     * insert update For Mysql
     * @param <type> $table
     * @param <type> $field_values
     * @param <type> $mode
     * @param <type> $where
     * @return <type>
     */
    public function autoExecute($table, $field_values, $mode = 'INSERT', $where = '')
    {
        $field_names = $this->getCol('DESC ' . $table);

        $sql = '';
        if ($mode == 'INSERT') {
            $fields = $values = array();
            foreach ($field_names AS $value) {
                if (array_key_exists($value, $field_values) == true) {
                    $fields[] = '`' . $value . '`';
                    $values[] = "'" . $field_values[$value] . "'";
                }
            }

            if (!empty($fields)) {
                $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
            }
        } else {
            $sets = array();
            foreach ($field_names AS $value) {
                if (array_key_exists($value, $field_values) == true) {
                    $sets[] = '`' . $value . "` = '" . $field_values[$value] . "'";
                }
            }

            if (!empty($sets)) {
                $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
            }
        }

        if ($sql) {
			if ($mode == 'INSERT') {
				if($this->execute($sql)){
					return mysql_insert_id($this->link);
				}else{
					return false;
				}
			}else{
            	return $this->query($sql);
			}
        } else {
            return false;
        }
    }
	/**
	 * 释放结果集
	 * @param resource $rs 结果集
	 * @return boolean
	 */
	public function free($rs)
	{
		return mysql_free_result ( $rs );
	}
	/**
	 * 查询数据库
	 * @return resource
	 */
	public function fetch($rs)
    {
        //return mysql_fetch_array($rs);
    	return mysql_fetch_array($rs,MYSQL_ASSOC);
    }
	/**
	 * 关闭数据库
	 * @access public
	 * @return boolean
	 */
	public function close()
	{
		return mysql_close ( $this->link );
	}
	/**
	 * 获取错误信息
	 * @return void
	 * @access public
	 */
	public function getError()
	{
		echo mysql_errno ( $this->link ) . " : " . mysql_error ( $this->link );
	}	
	/**
	 * 抛出一个异常信息
	 * @param string $message 异常信息
	 * @return void
	 */
	protected function throwException($message)
	{
		throw new Exception ( $message );
	}
	/**
	 * 释放结果集 
	 */
	public function freeResult() {
		$void = func_get_args();
		foreach($void as $query) {
			if(is_resource($query) && get_resource_type($query) === 'mysql result') {
				return mysql_free_result($query);
			}
		}
	}
	/**
	 * 析构函数--关闭数据库，释放资源 
	 */
	public function __destruct() {
		$this->freeResult();  
		$this->close();
	}
	//获取毫秒数
	public function microtime_float() {
		list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec + (float)$sec);
	}
}
